package avishay.balderman;

import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import avishay.balderman.dao.TeamMemberHelper;


public abstract class EmailHelper 
{
	public static void send(HttpServletRequest req) 
	{
			Properties props = new Properties();
	        Session session = Session.getDefaultInstance(props, null);
	        final String msgBody = req.getParameter("msgBody");
	        final String msgTitle = req.getParameter("msgTitle");	        
	        try 
	        {
	            Message msg = new MimeMessage(session);
	            msg.setFrom(new InternetAddress("dracing444@gmail.com", "Dynamo Racing Team Admin"));
	            msg.addRecipients(Message.RecipientType.TO, getTeamMembersMailAddresses());
	            msg.setSubject(msgTitle);
	            msg.setText(msgBody);
	            Transport.send(msg);
	        } 
	        catch (Exception e)
	        {
	        	logger.log(Level.SEVERE, "Failed to send mail.", e);
	        }
	}
	private static InternetAddress [] getTeamMembersMailAddresses() throws AddressException
	{
		List<String> emailAddresses = TeamMemberHelper.getEmailAddresses();
		InternetAddress [] result  = new InternetAddress[emailAddresses.size()];
		int count = 0;
		for(String addr : emailAddresses)
		{
			result[count] = new InternetAddress(addr);
			count++;
		}
		
		return result;
	}
	private static Logger logger = Logger.getLogger("avishay.balderman.dao.TeamMemberHelper");
}
